package ServiceProvider;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

public class BroadcastListener {

	int listenPort;
	InetAddress listenGroup;
	MulticastSocket listenSocket;
	DatagramPacket receivedPacket;
	byte[] receivedData = new byte[30];
	
	public BroadcastListener(String port, String bcGroup) {
		listenPort = Integer.parseInt(port);
		listenGroup = convertToInetAddress(bcGroup);
		initializeListenBroadcast();
	}

	private static InetAddress convertToInetAddress(String bcGroup) {
		try {
			return InetAddress.getByName(bcGroup);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private void initializeListenBroadcast() {
		try {
			listenSocket = new MulticastSocket(listenPort);
			receivedPacket = new DatagramPacket(receivedData, receivedData.length);
			listenSocket.joinGroup(listenGroup);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String receiveBroadcastMessage() {
		String message;
		
		try {
			listenSocket.receive(receivedPacket);
			message = new String(receivedPacket.getData(), 0, receivedPacket.getLength());
		} catch (IOException e) {
			message = "Receive Error";
			e.printStackTrace();
		}
		
		return message;
	}
	
}
